﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Chapter21_01
{
    using System.IO;
    using Microsoft.Win32;

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private FileSystemWatcher watcher;

        public MainWindow()
        {
            InitializeComponent();
            watcher = new FileSystemWatcher();
            watcher.Deleted += (s, e) => AddMessage("文件: {0}", e.FullPath);
            watcher.Renamed += (s, e) => AddMessage("文件重命名： {0} 更改为 {1}", e.OldName, e.Name);
            watcher.Changed += (s, e) => AddMessage("文件变更: {0} {1}", e.FullPath, e.ChangeType.ToString());
            watcher.Created += (s, e) => AddMessage("文件: {0} 已经创建", e.FullPath);
        }

        private void locationBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            watchButton.IsEnabled = !string.IsNullOrEmpty(locationBox.Text);
        }

        private void browseButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog(this) == true)
            {
                locationBox.Text = dialog.FileName;
            }

        }

        private void watchButton_Click(object sender, RoutedEventArgs e)
        {
            watcher.Path = Path.GetDirectoryName(locationBox.Text);
            watcher.Filter = Path.GetFileName(locationBox.Text);
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size;
            AddMessage("正在监视：" + locationBox.Text);
            watcher.EnableRaisingEvents = true;
        }

        private void AddMessage(string formatString, params string[] parameters)
        {
            Dispatcher.BeginInvoke(new Action(() => watchOuput.Items.Insert(0, string.Format(formatString, parameters))));
        }
    }
}
